<template>
	<view class="container" :style="'height:'+ winHeight+'px;'">
		<view class="login-head"></view>
		<view class="login-title" v-html="sys.sysName"></view>
		<view class="login-content">
			<view class="input-group">
				<view class="input-row" v-if="sys.isMultiTenant">
					<text class="title">租户号：</text>
					<input class="login-input" type="text" clearable focus v-model="user.tenantId" placeholder="请输入租户号"></input>
				</view>
				<view class="input-row">
					<text class="title">账号：</text>
					<input class="login-input" type="text" clearable focus v-model="user.userName" placeholder="请输入账号"></input>
				</view>
				<view class="input-row">
					<text class="title">密码：</text>
					<input class="login-input" type="password" v-model="user.password" placeholder="请输入密码"></input>
				</view>
				<view class="input-row" v-if="sys.isLoginVerifyCheckCode" style="padding-bottom: 10px;">
					<text class="title">验证码：</text>
					<input class="login-input" type="text" v-model="user.validateCode" placeholder="验证码"></input>

				</view>
				<view v-if="sys.isLoginVerifyCheckCode">
					<img :src="validateCodeSrc" id="ValidateCodeImg" style="cursor: pointer;margin-bottom: 10px;" alt="点击刷新" onclick="this.src=this.src+'&';" />
				</view>
			</view>
			<view class="btn-row">
				<button class="btn-primary" :loading="loading" @click="loginSubmit">登 录</button>
			</view>
		</view>
		<div style="margin-top: 20px">
			 <div class="copyRight" v-html="sys.copyRight"></div> 
		</div>
		
		<view class="oauth-row" v-if="hasProvider" v-bind:style="{top: positionTop + 'px'}">
			<view class="oauth-image" v-for="provider in providerList" :key="provider.value">
				<image :src="provider.image" @tap="loginByWeixin(provider.value)"></image>
				<!-- #ifdef MP-WEIXIN -->
				<button v-if="!isDevtools&&false" open-type="getUserInfo" @getuserinfo="getUserInfo"></button>
				<!-- #endif -->
			</view>
		</view>
	</view>
</template>

<script>
	import {
		encrypt,
		decrypt
	} from '@/utils/crypto-js.js';
	import {
		mapState,
		mapMutations
	} from 'vuex'
	let weixinAuthService
	export default {
		computed: mapState(['forcedLogin', "__serverpath"]),
		onLoad: function(option) { //option为object类型，会序列化上个页面传递的参数
			console.log(option.id); //打印出上个页面传递的参数。
			console.log(option.name); //打印出上个页面传递的参数。
		},
		created() {
			var that = this;
			that.serverpath=__serverpath;
			that.user.vCodeKey = "ValidateCode_" + Object.toGuid();
			that.validateCodeSrc = __serverpath + "/login/validateCode/?vCodeKey=" + that.user.vCodeKey;
			that.$store.commit('logout')
			uni.getSystemInfo({
				success: function(res) {
					// console.log(res.model);
					// console.log(res.pixelRatio);
					// console.log(res.windowWidth);
					// console.log(res.windowHeight);
					that.winHeight = res.windowHeight;
					// console.log("winHeight:"+that.winHeight);
					// console.log(res.language);
					// console.log(res.version);
					// console.log(res.platform);
				}
			});
			try {
				uni.request({
					url: that.serverUrl + '/login/getLoginPageData',
					success: function(res) {
						var resData = res.data;
						if (resData.success) {
							that.sys = resData.data;
							var f2bpmSysConfig = that.sys;
							that.$store.commit('f2bpmSysConfig', f2bpmSysConfig)
						} else {
							uni.showModal({
								showCancel: false,
								content: resData.msg,
							});
						}
					},
					fail: function(res) {
						console.info(res);
					}
				});
			} catch (err) {
				alert(err)
			}
		},
		data() {
			return {
				validateCodeSrc: "",
				positionTop: 0,
				providerList: [],
				loading: false,
				hasProvider: false,
				winHeight: 800,
				user: {
					vCodeKey: '',
					validateCode: '',
					loginType: 'mobile',

					tenantId: '',
					userName: '',
					password: '',

					//接入的系统应用ID
					corpId: "AppDefault"
				},
				sys: {}

			}
		},
		methods: {
			// 映射到state中的mutations中的loginauthor
			...mapMutations(['loginauthor']),
			initProvider() {
				var that = this;
				const filters = ['weixin', 'qq', 'sinaweibo'];
				uni.getProvider({
					service: 'oauth',
					success: (res) => {
						if (res.provider && res.provider.length) {
							for (let i = 0; i < res.provider.length; i++) {
								if (~filters.indexOf(res.provider[i])) {
									that.providerList.push({
										value: res.provider[i],
										image: '../../static/images/icons/' + res.provider[i] + '.png'
									});
								}
							}
							this.hasProvider = true;
						}
					},
					fail: (err) => {
						console.error('获取服务供应商失败：' + JSON.stringify(err));
					}
				});
			},
			initPosition() {
				/**
				 * 使用 absolute 定位，并且设置 bottom 值进行定位。软键盘弹出时，底部会因为窗口变化而被顶上来。
				 * 反向使用 top 进行定位，可以避免此问题。
				 */
				this.positionTop = uni.getSystemInfoSync().windowHeight - 100;
			},
			sendSmsCode() {

			},
			loadValidateCode() {
				var that = this;
				that.validateCodeSrc = that.validateCodeSrc + "&ram=" + Object.toGetCurrentDateTimeMillisecond();
			},
			loginSubmit() {
				let that = this;
				if (that.user.userName === '' || that.user.password === '') {
					uni.showToast({
						icon: 'none',
						title: '请输入账号、密码'
					});
					return false;
				}
				try {
					//===使用自己的ajax======
					uni.showLoading({
						mask: true,
						title: "登录中..."
					});
					var colneUser = Object.toDeepClone(that.user);
					colneUser.password = encrypt(colneUser.password);
					uni.request({
						url: that.serverUrl + '/login/loginByAndPassword',
						data: colneUser,
						method: 'POST',
						header: {
							'Content-type': 'application/x-www-form-urlencoded'
						},
						success: function(res) {
							var result = res.data;
							if (result.success) {
								let author = result.data;
								//author.realName=decodeURI(author.realName);
								that.$store.commit('loginauthor', author)
								that.loginLocal(author.userId)
							} else {
								that.$store.commit('logout');
								uni.showModal({
									showCancel: false,
									content: result.msg,
								});
								that.loadValidateCode();
							}
						},
						complete: () => {
							uni.hideLoading();
						},
						fail: function(res) {
							if (res.errMsg.indexOf("ERR_CONNECTION_REFUSED")) {
								uni.showToast({
									icon: 'none',
									title: '网络错误，请求失败'
								});
							}
							uni.hideLoading();
						}
					});
				} catch (e) {
					uni.showModal({
						content: '请求异常' + e.toString()
					})
				}


			},
			loginLocal(userId) {
				uni.setStorageSync('login_type', 'local')
				this.toMain();
			},
			toMain() {
				if (this.forcedLogin) {
					uni.reLaunch({
						url: '../home/index',
					});
				} else {
					uni.navigateBack();
				}
			},
			oauth(value) {
				if (value !== 'weixin') {
					//非微信登录
					uni.showModal({
						content: `${value}登录只演示登录api能力，暂未关联云端数据`,
						showCancel: false
					})
					console.log(`${value}登录只演示登录api能力，暂未关联云端数据`);
					uni.login({
						provider: value,
						success: (res) => {
							uni.getUserInfo({
								provider: value,
								success: (infoRes) => {
									/**
									 * 实际开发中，获取用户信息后，需要将信息上报至服务端。
									 * 服务端可以用 userInfo.openId 作为用户的唯一标识新增或绑定用户信息。
									 */
									this.loginLocal(infoRes.userInfo.nickName);
								},
								fail() {
									uni.showToast({
										icon: 'none',
										title: '登陆失败'
									});
								}
							});
						},
						fail: (err) => {
							console.error('授权登录失败：' + JSON.stringify(err));
						}
					});
					return;
				}

				return new Promise((resolve, reject) => {
					// #ifdef APP-PLUS
					weixinAuthService.authorize(function(res) {
						resolve(res.code)
					}, function(err) {
						console.error(err)
						reject(new Error('微信登录失败'))
					});
					// #endif
					// #ifdef MP-WEIXIN
					uni.login({
						provider: 'weixin',
						success(res) {
							resolve(res.code)
						},
						fail(err) {
							console.error('授权登录失败：' + JSON.stringify(err));
							reject(new Error('微信登录失败'))
						}
					})
					// #endif
				})
			},
			getUserInfo({
				detail
			}) {
				console.log('三方登录只演示登录api能力，暂未关联云端数据');
				if (detail.userInfo) {
					console.info(detail)
					this.loginLocal(detail.userInfo.nickName);
				} else {
					uni.showToast({
						icon: 'none',
						title: '登陆失败'
					});
				}
			},
			loginByWeixin(value) {
				var that = this;
				//手机微信第三方登录：value值为weixin
				uni.showLoading({
					mask: true,
					title: "登录中..."
				});
				this.oauth(value).then((code) => {
					//通过云端云获取微信的openId,这里也可以将code转给后端，由后端去微信上换openId
					return uniCloud.callFunction({
						name: 'user-center',
						data: {
							action: 'loginByWeixin',
							params: {
								code,
							}
						}
					})
				}).then((res) => {
					if (res.result.code === 0) {
						//从后台请求对应登录
						uni.request({
							url: that.serverUrl + '/login/loginByWeixin',
							data: {
								corpId: that.user.corpId,
								uid: res.result.uid,
								sessionKey: res.result.sessionKey,
								token: res.result.token
							},
							success: function(res) {
								var result = res.data;
								if (result.success) {
									let author = result.data;
									that.$store.commit('loginauthor', author)
									that.loginLocal(author.userId)
								} else {
									if (result.status != undefined) {
										result.msg = result.error;
									}
									that.$store.commit('logout')
									uni.showModal({
										showCancel: false,
										content: result.msg,
									});
								}
							},
							complete: () => {
								uni.hideLoading();
							},
							fail: function(res) {
								console.info(res);
							}
						});



						// uni.setStorageSync('uni_id_token', res.result.token)
						// uni.setStorageSync('uni_id_token_expired', res.result.tokenExpired)
					}
				}).catch((e) => {
					console.error(e)
					uni.showModal({
						showCancel: false,
						content: '微信登录失败，请稍后再试'
					})
				})
			},
		},
		onReady() {
			this.initPosition();
			this.initProvider();
			// #ifdef MP-WEIXIN
			this.isDevtools = uni.getSystemInfoSync().platform === 'devtools';
			// #endif
		}
	}
</script>

<style>
	@import url("@/static/css/login.css");
</style>
